#include "../include/login.h"
#define rt_login_0 "用户登录成功" //登录返回值:普通用户
#define rt_login_1 "管理员登录成功" //登录返回值:管理员
#define rt_register "注册成功" //注册返回值

TRAN m_node;
char buff[1024];
int client_login(int sel,int client_socket)//客户端登录/注册函数
{
	
	//登录/注册
	bzero(&m_node,sizeof(m_node));
	printf("已进入登录界面\n");
	printf("请输入用户名:");
	scanf("%s",m_node.name);
	while(1){
		printf("请输入用户密码(至少为3位字符):");
		scanf("%s",m_node.pas);
		if(strlen(m_node.pas)<3){
			puts("密码长度不足");
			continue;
		}
		break;
	}
	//向服务端发送登录/注册请求
	if(sel==1)
		strcpy(m_node.order,"login");
	else if(sel==2)
		strcpy(m_node.order,"register");
		
	packJson(&m_node);

	printf("准备向服务端发送信息:%s\n",buff);
	write(client_socket,buff,strlen(buff));
	
	
	puts("准备从服务器接收返回值");
	bzero(buff,sizeof(buff));
	sleep(2);
	int num=read(client_socket,buff,1024);
	if(num<=0){
		puts("已超时,未能接收到返回值");
		return -1;
	}
	else
		printf("接收到返回值:%s\n",buff);
	if(strcmp(rt_login_0,buff)==0){
		m_node.perm=0;
		return 0;
	}else if(strcmp(rt_login_1,buff)==0){
		m_node.perm=1;
		return 1;
	}
	if(strcmp(rt_register,buff)==0)
		return 2;
	else
		return -1;
}
void packJson(TRAN *head)
{
	cJSON* root = cJSON_CreateObject();
	cJSON* order = cJSON_CreateString(head->order);
	cJSON* name = cJSON_CreateString(head->name);
	cJSON* pas = cJSON_CreateString(head->pas);
	cJSON* newpas = cJSON_CreateString("");

	cJSON_AddItemToObject(root,"order",order);
	cJSON_AddItemToObject(root,"name",name);
	cJSON_AddItemToObject(root,"pwd",pas);
	cJSON_AddItemToObject(root,"new_pwd",newpas);
	
	char *p=buff;
	p=cJSON_Print(root);
	strcpy(buff,p);
	cJSON_Delete(root);
}
